package stdio.costa.imoca.task;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import stdio.costa.imoca.card.A3PreviewBuilder;
import stdio.costa.imoca.model.Postcard;
import stdio.costa.imoca.model.Preview;

@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class A3MakerTask {

	private static final Logger logger = LoggerFactory.getLogger(A3MakerTask.class);

	private static final int CARDS_PER_PAGE = 8;

	@PersistenceContext
	private EntityManager entityManager;

	@SuppressWarnings("unchecked")
	@Transactional
	@Async
	public void findAndMake() {
		logger.info("Finding and making A3...");
		Query query = entityManager.createNamedQuery("Postcard.readyToPrint").setMaxResults(CARDS_PER_PAGE);
		List<Postcard> postcards = query.getResultList();
		if (postcards.size() == CARDS_PER_PAGE) {
			try {
				Preview preview = new A3PreviewBuilder(postcards.get(0) , postcards.get(1), postcards.get(2), postcards.get(3), postcards.get(4), postcards.get(5), postcards.get(6), postcards.get(7)).build();
				entityManager.persist(preview);
				updatePostcard(postcards.get(0), preview);
				updatePostcard(postcards.get(1), preview);
				updatePostcard(postcards.get(2), preview);
				updatePostcard(postcards.get(3), preview);
				updatePostcard(postcards.get(4), preview);
				updatePostcard(postcards.get(5), preview);
				updatePostcard(postcards.get(6), preview);
				updatePostcard(postcards.get(7), preview);
				print(preview);
			} catch (Exception e) {
				logger.error("Failed to build A3.", e);
			}
			logger.info("A3 has been made.");
		}
	}
	
	protected void updatePostcard(Postcard postcard, Preview preview) {
		postcard.setPrintedPreview(preview);
		entityManager.merge(postcard);
	}
	
	protected void print(Preview preview) {
		// FIXME send preview images into a particular directory or ?
	}
}
